var holidayManage = {
    events : {
        ".holidayManage-body .department-control click" : "dropdownControl",
        ".holidayManage-body .department-control blur" : "dropdownControlHide",
        ".holidayManage-body .add-holiday click" : "addHoliday",
        ".holidayManage-body .update-holiday click" : "updateHoliday",
        ".holidayManage-body .delete-holiday click" : "deleteHoliday",
        ".holidayManage-body .department-item click" : "selectDepartment",
        ".holidayManage-body .department-field DOMSubtreeModified" : "changeDepartment",
        ".holidayManage-body #curYear DOMSubtreeModified" : "changeYear",
        ".holidayManage-body .detail click" : "showDetail"
    },
    curDepartMent : null,
    curDate : {
        year : new Date().getFullYear(),
        month : new Date().getMonth() + 1
    },
	init : function(){
		var _this = this;
        document.title = "节假日管理 - 考勤管理";
        var temp = Util.template($("#holidayManage-template").html(),{});
        $(".commonBody-rightBody").html(temp);
        Util.event.call(_this,_this.events);
        this.getDeptList();
	},
    getDeptList : function(){
        var that = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getHolidayDeptList(),
            dataType: "json",
            showLoading : false,
            success : function(data){
                if(data.code == 200){
                    that.treeNodes = data.result;
                    that.holidayList();
                    that.allHoliday();
                }
            }
        })
    },
	holidayList : function(){
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getHolidayList(),
            dataType: "json",
            showLoading : false,
            success : function(data){
                if(data.code == 200){
                    var columns = data.result;
                    $.each(columns,function(i,v){
                        v.range = new Date(v.startDate).format("yyyy-MM-dd") + "~" + new Date(v.endDate).format("yyyy-MM-dd")
                        v.operation = '<button class="btn btn-blue detail">详情</button>';
                    })
                    $(".holiday-table").cakeTable({
                        head: [
                            {field: "name",name: "名称"},
                            {field: "range",name: "起止日期"},
                            {field: "operation",name: "适用对象",type:2}
                        ],
                        rowData : [{key:"id",attrName:"data-id"}],
                        numType : 2,
                        sort: false,
                        columns: columns,
                        showPage:false,
                        patch : true
                    })
                }
            }
        })
        
	},
    allHoliday : function(){
        // console.log(this.curDepartMent);
        var temp = Util.template($("#rili-template").html(),{
            curDate:this.curDate,
            dept : this.treeNodes,
            department : this.curDepartMent
        });
        $(".holiday-picker-box").html(temp);
        if(!this.curDepartMent){
            this.curDepartMent = {
                id : this.treeNodes[0].id,
                name : this.treeNodes[0].name
            }
        }
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.findDetailByDepId(),
            dataType: "json",
            showLoading : false,
            data : {
                depId : this.curDepartMent.id,
                year : this.curDate.year
            },
            success : function(data){
                if(data.code == 200){
                    var dateRest = data.result.dateRest;
                    var dateWork = data.result.dateWork;
                    initRiLi(dateRest,dateWork);
                }
            }
        })
    },
    renderTree : function(check){
        var setting = {
            check: {
                enable: true,
                chkboxType: { "Y": "s", "N": "" }
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback : {
                beforeCheck : function(){
                    return check;
                }
            }
        };
        this.zTreeObj = $.fn.zTree.init($("#treeList"), setting, this.treeNodes);
        this.zTreeObj.expandAll(true);
    },
    addHoliday : function(ele){
        this.showHolidayPop(null,1);
    },
    updateHoliday : function(){
        var checked = $(".property[name=tableCheck]").find(".checked"),
            that = this;
        if(checked.length!=1){
            pop.alert("请勾选一项节假日再进行修改！");
        }else{
            var id = checked.parents("tr").attr("data-id");
            this.getDetail(id,2);
        }
    },
    showDetail : function(ele){
        var id = $(ele).parents("tr").attr("data-id");
        this.getDetail(id,3);
    },
    getDetail : function(id,type){
        var that = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getHolidayById(),
            dataType: "json",
            showLoading : false,
            data : {id:id},
            success : function(data){
                if(data.code == 200){

                    that.showHolidayPop(data.result,type);
                }
            }
        })
    },
    showHolidayPop : function(data,type){
        var that = this;
        pop.dialog({
            popTitle: type == 1 ? "节假日新增" : type == 2 ? "节假日修改" : "节假日详情",
            popContent: Util.template($("#add-holiday-tempalte").html(), {data : data}),
            width :　"595px",
            maxHeight : "500px",
            popOkText : type != 3 ? "提交" : "关闭",
            popCancelShow : type != 3 ? true : false,
            onLoad: function () {
                if(type != 3){
                    $(".date-from").datetimepicker({
                        format: 'yyyy-mm-dd',
                        autoclose: true,
                        language: "zh-CN",
                        pickerPosition: "bottom-left",
                        minView:2
                    });
                    that.renderTree(true);
                }else{
                    $(".add-holiday-body").find("input,textarea").attr("readonly",true);
                    $(".plus-btn,minus-btn").remove();
                    that.renderTree(false);
                }
                $(".plus-btn").click(that.addRow);
                $(".pop-container").delegate(".minus-btn","click",that.deleteRow);
                if(data){
                    for(var i=0;i<data.depIds.length;i++){
                        var node = that.zTreeObj.getNodeByParam("id",data.depIds[i]);
                        that.zTreeObj.checkNode(node, true, false);
                    }
                }
            }
        },function(){
            if(type != 3){
                return that.saveHoliday();
            }   
        })
    },
    deleteHoliday : function(){
        var checked = $(".property[name=tableCheck]").find(".checked");
        var ids = "";
        var that = this;
        $.each(checked , function(i,v){
            var id = $(v).parents("tr").attr("data-id");
            ids = ids == ""? id : ids + "," + id;
        })
        if(ids == ""){return false;}
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.deleteHolidays(),
            dataType: "json",
            showLoading : false,
            data : {ids:ids},
            success : function(data){
                if(data.code == 200){
                    that.holidayList();
                    that.allHoliday();
                }
            }
        })
    },
    addRow : function(){
        var temp = Util.template($("#date-form-tempalte").html(), {});
        $(".input-row.multiple").append(temp);
        $(".date-from").datetimepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            language: "zh-CN",
            pickerPosition: "bottom-left",
            minView:2
        });
    },
    deleteRow : function(){
        $(this).parents(".date-time-row").remove();
    },
    saveHoliday : function(){
        var obj = Util.getData($(".add-holiday-body")),that = this;
        obj.depIds = "";
        var nodes = this.zTreeObj.getCheckedNodes(true);
        $.each(nodes, function(i,v){
            obj.depIds = obj.depIds == "" ? v.id : obj.depIds + "," + v.id;
        })
        var tempArray = [];
        $(".multiple").find(".date-time-row").each(function(){
            var startDate = $(this).find(".work-start").val(),
                endDate = $(this).find(".work-end").val();
            tempArray.push({startDate:startDate,endDate:endDate})
        });
        obj.workday = JSON.stringify(tempArray);
        obj.id = $(".add-holiday-body").attr("data-id");
        if(Util.isEmpty(obj.name,obj.startDate,obj.endDate,obj.depIds)){
            pop.alert("节假日名称、放假日期、执行对象不能为空，请填写完成后提交!");
            return false;
        }
        Util.ajaxRequest({
            type: "post",
            url: interfaceURL.saveHoliday(),
            dataType: "json",
            showLoading : false,
            data : obj,
            success : function(data){
                if(data.code == 200){
                    that.holidayList();
                    that.allHoliday();
                }
            }
        })
    },
    dropdownControl : function (ele){
        var list = $(ele).parent().find(".department-list");
        if(list.css("display") == "none"){
            list.css("display","block");
        }else{
            list.css("display","none");
        }
    },
    dropdownControlHide : function(ele){
        var list = $(ele).parent().find(".department-list");
        list.css("display","none");
    },
    selectDepartment : function(ele){
        $(".department-item").removeClass("on");
        $(ele).addClass("on");
        if(this.curDepartMent && this.curDepartMent.id == $(ele).attr("val")){
            return false;
        }
        this.curDepartMent = {
            id : $(ele).attr("val"),
            name : $(ele).text()
        }
        $(".department-field").text($(ele).text());
    },
    changeDepartment : function(ele){
        this.allHoliday()
    },
    changeYear : function(ele){
        var year = $(ele).text().substring(0,4);
        if(Util.isEmpty(year) || this.curDate.year == year){
            return false;
        }else{
            if(parseInt(this.curDate.year) > parseInt(year)){
                this.curDate.month = "12";
            }else{
                this.curDate.month = "01";
            }
            this.curDate.year = year;
        }
        console.log(this.curDate);
        this.allHoliday();
    }
};